package com.easyaop.api.support.loadclass;

import com.easyaop.api.support.ClassDefiner;

import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;

public abstract class AbstractClassDefiner implements ClassDefiner {
    protected int majorVersion;

    protected Class<?> targetClass;

    protected MethodHandles.Lookup caller;

    public AbstractClassDefiner(MethodHandles.Lookup caller, Class<?> targetClass) {
        this.majorVersion = MajorVersion.getMajorVersion();
        this.targetClass = targetClass;
        this.caller = caller;
    }

    public AbstractClassDefiner(int majorVersion, MethodHandles.Lookup caller, Class<?> targetClass) {
        this.majorVersion = majorVersion;
        this.targetClass = targetClass;
        this.caller = caller;
    }

    @Override
    public int majorVersion() {
        return majorVersion;
    }

    public static class MajorVersion {
        public static int getMajorVersion() {
            try {
                Class<?> versionClass = Class.forName("java.lang.Runtime");
                Method method = versionClass.getMethod("version");
                Object version = method.invoke(null);
                Method majorVersionMethod = version.getClass().getMethod("major");
                return (int) majorVersionMethod.invoke(version);
            } catch (Exception ex) {
            }
            return convertJdkVersionToMajor(System.getProperty("java.version"));
        }

        private static int convertJdkVersionToMajor(String versionString) {
            if (versionString == null || !versionString.startsWith("1.")) {
                throw new IllegalArgumentException("Invalid JDK version string: " + versionString);
            }
            String[] parts = versionString.split("\\.");
            if (parts.length < 2) {
                throw new IllegalArgumentException("Invalid JDK version string: " + versionString);
            }
            return Integer.parseInt(parts[1]);
        }
    }
}